//
//  LatestViewController.m
//  LiveDailyNews
//
//  Created by smu on 11-7-19.
//  Copyright 2011年 duk. All rights reserved.
//

#import "LatestViewController.h"
#import "Constant.h"
#import "RSSItem.h"
#import "WebViewController.h"
#import "FirstCell.h"
#import "CustomCell.h"

@implementation LatestViewController
@synthesize itemList;

@synthesize rssItem;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //工具栏，当前选项卡
        self.tabBarItem.title = @"最新";
        UIImage *imageTab = [[UIImage alloc] initWithContentsOfFile:
                             [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"TAB_ICON_CHAT.png"]];
		self.tabBarItem.image = imageTab;
		[imageTab release];
        
        //导航栏添加内容
        //左边logo
        UIImage *logoImage = [[UIImage alloc] initWithContentsOfFile:[
                                [[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Logo.png"]];
        UIImageView *logoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 32)];  
        logoImageView.image = logoImage;
        [logoImage release];
        UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:logoImageView]; 
        [logoImageView release];
        self.navigationItem.leftBarButtonItem = leftBarButton;
        [leftBarButton release];
        
        //中间标题
        self.navigationItem.title = @"最新";
        
        //右边刷新按钮
        refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self 
                                                                      action:@selector(refreshList:)];
        [[self navigationItem] setRightBarButtonItem:refreshButton];
        //ActivityIndicator
        spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        // I do this because I'm in landscape mode        
        [spinner setCenter:CGPointMake(320/2.0, 480/2.0)];
        // spinner is not visible until started
        [self.view addSubview:spinner];
        
        mParser = [[RSSParser alloc] init];
        [mParser parse:RSS_LATEST_URL withDelegate:self onComplete:@selector(refreshTable:)];
        
    }
    return self;
}

- (void)viewDidLoad
{
    
    UIView *contentView = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
	
	contentView.autoresizesSubviews = YES;
	self.view = contentView;
	[self.view setBackgroundColor:[UIColor clearColor]];
    
	CGRect frame = contentView.frame;
	frame.origin.x = 0;
	frame.origin.y = contentView.bounds.size.height - frame.size.height;
	frame.size.width = contentView.bounds.size.width;
	frame.size.height = contentView.bounds.size.height - 44 - 48;
	
	mtableView = [[UITableView alloc] initWithFrame:frame style:UITableViewCellStyleDefault];
	mtableView.delegate = self;
	mtableView.dataSource = self;
	mtableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
	mtableView.scrollEnabled = YES;
	[mtableView setBackgroundColor:[UIColor clearColor]];
    
	[self.view addSubview:mtableView];
    
    [super viewDidLoad];
    
    //初始,下载数据
    [refreshButton setEnabled:NO];
    [spinner startAnimating];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}        


// This refreshes the feeds when the refresh button is tapped.
- (void)refreshList:(id)sender {
    [refreshButton setEnabled:NO];
	[spinner startAnimating];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
	[mParser release];
    mParser = [[RSSParser alloc] init];
    
//    //获取整个手机屏幕
//    UIView *contentView = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
//	
//    
//	
//    //禁止用户操作界面
//    self.view.userInteractionEnabled = FALSE;
    
	[mParser parse:RSS_LATEST_URL withDelegate:self onComplete:@selector(refreshTable:)];
//    [contentView release];
    
}

- (void)refreshTable:(RSSParser *)objectParser {
    //判断网络连接，获取数据是否成功
    
    //返回成功
    self.itemList = [objectParser getItems];
    
	[mtableView reloadData];
    
    //重新设置刷新状态
	[refreshButton setEnabled:YES];
	[spinner stopAnimating];
    self.view.userInteractionEnabled = TRUE;
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
    self.itemList = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc
{
    [itemList release];
    [spinner release];
    [refreshButton release];
    [mtableView release];
    [super dealloc];
}

#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.itemList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    NSUInteger row = [indexPath row];
    rssItem = [itemList objectAtIndex:row];
    static NSString *tableIdentifier;
    
    if (row == 0) {
        tableIdentifier = @"FirstTableIdentifier";
        FirstCell *cell = (FirstCell *)[tableView dequeueReusableCellWithIdentifier:tableIdentifier];
        if (cell == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FirstCell" owner:self options:nil];
            for (id oneObject in nib)
                if ([oneObject isKindOfClass:[FirstCell class]]) {
                    cell = (FirstCell *)oneObject;
                }
        }
        
        cell.titleLabel.text = rssItem.title;
        
        UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:rssItem.imagePath]]];
        cell.backgroundImageView.image = image;
        cell.descripLabel.text = rssItem.description;
        return cell;
    } else {
        tableIdentifier = @"CustomTableIdentifier";
        CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:tableIdentifier];
        if (cell == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
            for (id oneObject in nib)
                if ([oneObject isKindOfClass:[CustomCell class]]) {
                    cell = (CustomCell *)oneObject;
                }
            cell.titleLabel.text = rssItem.title;
            
            UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:rssItem.imagePath]]];
            cell.itemImageView.image = image;
            cell.descripLabel.text = rssItem.description;
            return cell;
        } else {
            return cell;
        }
        
       
    }
    [rssItem release];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    rssItem = [itemList objectAtIndex:row];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:rssItem.title forKey:@"title"];
    [userDefaults setObject:rssItem.link forKey:@"link"];
    [userDefaults setObject:rssItem.content forKey:@"content"];
    [userDefaults setObject:rssItem.imagePath forKey:@"imagePath"];
    [userDefaults setObject:rssItem.pubDate forKey:@"pubDate"];
    [userDefaults setObject:rssItem.category forKey:@"category"];
    [userDefaults setObject:rssItem.description forKey:@"description"];
    WebViewController *webView = [[WebViewController alloc] init];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webView animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([indexPath row] == 0) {
        return 160;
    } else {
        return 70;
    }
}

@end
